package model

import (
	"gorm.io/gorm"
)

// Attachment 附件模型
type Attachment struct {
	gorm.Model
	UserID         int64  `gorm:"type:bigint;not null;index;comment:用户ID"`
	UserType       int    `gorm:"type:tinyint(1);not null;comment:用户类型:1-医生,2-患者"`
	AttachmentType int    `gorm:"type:tinyint(1);not null;comment:附件类型:1-资格证,2-病历资料,3-检查报告"`
	FileName       string `gorm:"type:varchar(255);not null;comment:文件名"`
	FileUrl        string `gorm:"type:varchar(255);not null;comment:文件URL"`
	FileSize       int64  `gorm:"type:bigint;comment:文件大小(字节)"`
}

// AttachmentPermission 附件权限
type AttachmentPermission struct {
	gorm.Model
	AttachmentID     int64 `gorm:"type:bigint;not null;index;comment:附件ID"`
	AuthorizedUserID int64 `gorm:"type:bigint;not null;comment:授权用户ID"`
}

// CreateAttachment 创建附件
func (a *Attachment) CreateAttachment(db *gorm.DB) error {
	return db.Create(&a).Error
}

// GetAttachmentList 获取附件列表
func GetAttachmentList(db *gorm.DB, userId int64, attachmentType, page, pageSize int) ([]Attachment, int64, error) {
	var attachments []Attachment
	var total int64

	query := db.Model(&Attachment{}).Where("user_id = ?", userId)

	if attachmentType > 0 {
		query = query.Where("attachment_type = ?", attachmentType)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 使用分页作用域
	if err := query.Scopes(Paginate(page, pageSize)).Order("created_at DESC").Find(&attachments).Error; err != nil {
		return nil, 0, err
	}

	return attachments, total, nil
}

// SetAttachmentPermissions 设置附件权限
func SetAttachmentPermissions(db *gorm.DB, attachmentId int64, authorizedUserIds []int64) error {
	// 先删除旧的权限
	if err := db.Where("attachment_id = ?", attachmentId).Delete(&AttachmentPermission{}).Error; err != nil {
		return err
	}

	// 添加新的权限
	for _, userId := range authorizedUserIds {
		permission := AttachmentPermission{
			AttachmentID:     attachmentId,
			AuthorizedUserID: userId,
		}
		if err := db.Create(&permission).Error; err != nil {
			return err
		}
	}

	return nil
}

